<template>
  <div ref="statsVc"></div>
  <div class="container" ref="containerVc"></div>
</template>


<script setup lang="ts">
import {onMounted, ref} from "vue";
import {
  AxesHelper, BoxGeometry,
  Color,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  PlaneGeometry,
  Scene, SphereGeometry, SpotLight,
  WebGLRenderer
} from "three";
import Stats from "stats.js"

//拿到引用
let containerVc = ref<HTMLDivElement>();
let statsVc = ref<HTMLDivElement>();

//添加性能监控
let stats = new Stats()
stats.showPanel(0)

//创建场景
let scene = new Scene();

//创建摄像机
let camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
camera.position.set(-30, 40, 30)//摄像机位置
camera.lookAt(scene.position);//摄像机朝向


//设置渲染器
let renderer = new WebGLRenderer()
renderer.setClearColor(new Color(0xeeeeee))
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true;

//添加光照
let sportLight = new SpotLight(0xffffff)
sportLight.castShadow = true;
sportLight.position.set(-20, 60, -10)
scene.add(sportLight)


//添加一个坐标系
let axes = new AxesHelper(20)
scene.add(axes)


//添加一个平面
let planeGeo = new PlaneGeometry(60, 20)//创建一个平面
let mt_plane = new MeshBasicMaterial({color: 0xcccccc})//材质
let plane = new Mesh(planeGeo, mt_plane)//用指定材质创建一个网格

//设置平面的Transform
plane.rotation.x = -0.5 * Math.PI
// plane.position.x = 15
// plane.position.y = 0
// plane.position.z = 0
plane.receiveShadow = true
scene.add(plane)

//添加Cube
let cubeGeo = new BoxGeometry(4, 4, 4)
let mt_cube = new MeshBasicMaterial({color: 0xff0000, wireframe: false})//wireframe:线框
let cube = new Mesh(cubeGeo, mt_cube)
cube.position.set(2, 2, 2)
cube.castShadow = true;
scene.add(cube)

//创建一个球体
let sphereGeo = new SphereGeometry(4);
let mt_sphere = new MeshBasicMaterial({
  color: 0x7777ff,
  wireframe: false
})
let sphere = new Mesh(sphereGeo, mt_sphere)
sphere.castShadow = true
sphere.position.set(20, 3, 5);
scene.add(sphere)

//每帧渲染
let step = 0;
const renderScene = () => {
  //性能监控
  stats.update()

  cube.rotation.x += 0.02;
  cube.rotation.y += 0.02;
  cube.rotation.z += 0.05;

  step += 0.04;
  sphere.position.x = 20 + 10 * Math.cos(step);
  sphere.position.y = 2 + 10 * Math.abs(Math.sin(step));

  //递归渲染
  requestAnimationFrame(renderScene)
  renderer.render(scene, camera)
}
renderScene()


//挂载完后初始化完Div标签后再进行添加
onMounted(() => {
  containerVc.value?.appendChild(renderer.domElement)//将渲染出来的东西添加到Vc
  // stats.dom.style.top = "50px";
  statsVc.value?.appendChild(stats.dom);
  renderer.render(scene, camera);
})


</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  width: 100vw;
}
</style>